package com.tencent.iov.cowin.befsale.clue.value.utils;

import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.util.EmptyUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: Caychen
 * @Date: 2021/12/24 14:01
 * @Description:
 */
public class FileUtils {

    private static FileItem createFileItem(File file){
        int bytesRead;
        byte[] buffer = new byte[8192];
        FileItem item;
        try (FileInputStream fis = new FileInputStream(file)) {
            FileItemFactory factory = new DiskFileItemFactory(16, null);
            String filename = file.getName();
            item = factory.createItem("file", "text/html", false, filename);

            try (OutputStream os = item.getOutputStream()) {
                while ((bytesRead = fis.read(buffer, 0, buffer.length)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.flush();
            }
            return item;
        } catch (IOException e) {
            throw new BusinessException(NEError.BUSINESS_ERROR, e.getMessage());
        }

    }
    public static MultipartFile getMulFile(File file) {
        FileItem fileItem = createFileItem(file);
        return new CommonsMultipartFile(fileItem);
    }
}
